package com.tongtailian.www.stir.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuml
 * @explain
 * @time 2021/3/21 16:23
 */
public class HexUtil {



    /**
     * 将16进制字符串转换为byte[]
     *
     * @param hexString String
     * @return byte[]
     */
    public static byte[] hexString2ByteArray(String hexString) {
        try {
            if (hexString == null || hexString.equals("")) {
                return null;
            }
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];
            for (int i = 0; i < length; i++) {
                int pos = i * 2;
                d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
            }
            return d;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 字节转成HEX字符串
     *
     * @param src byte[]
     * @return String
     */
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (byte aSrc : src) {
            int v = aSrc & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 校验和必然是256的整数倍,如果有余数则认为校验和失败
     *
     * @return false 校验失败 反正成功
     */
    private static boolean checkValue(String hexLineStr) {
        byte[] buf = hexString2ByteArray(hexLineStr.substring(1));
        if (buf == null) {
            return false;
        }
        byte temp = 0;
        for (byte aBuf : buf) {
            temp += aBuf;
        }
        return temp % 0xFF == 0;
    }

    /**
     * 字符串(命令、长度、数据)按位异或
     *
     * @param hexString String  Eg: 05 0300 0800 05
     * @return String
     */
    private static String toXorString(String hexString) {
        hexString = change(hexString);
        String[] b = hexString.split(" ");
        int a = 0;
        for (String aB : b) {
            a = a ^ Integer.parseInt(aB, 16);
        }
        if (a < 10) {
            return "0" + a;
        }
        return String.format("%02X", a);
    }

    /**
     * 按照2字符一组分割成字符串
     *
     * @param content String
     * @return String
     */
    private static String change(String content) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < content.length(); i++) {
            if (i % 2 == 0) {
                str.append(" ").append(content.substring(i, i + 1));
            } else {
                str.append(content.substring(i, i + 1));
            }
        }
        return str.toString().trim();
    }

    /**
     * 16进制转10进制
     *
     * @param content String
     * @return int
     */
    public static int covert16to10(String content) {
        int number = 0;
        String[] HighLetter = {"A", "B", "C", "D", "E", "F"};
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i <= 9; i++) {
            map.put(i + "", i);
        }
        for (int j = 10; j < HighLetter.length + 10; j++) {
            map.put(HighLetter[j - 10], j);
        }
        String[] str = new String[content.length()];
        for (int i = 0; i < str.length; i++) {
            str[i] = content.substring(i, i + 1);
        }
        for (int i = 0; i < str.length; i++) {
            number += map.get(str[i]) * Math.pow(16, str.length - 1 - i);
        }
        return number;
    }

    /**
     * 字符串字节进行高低位转换
     *
     * @param hex String 原字节字符串
     * @return String 结果字节字符串
     */
    public static String reverseHex(String hex) {
        char[] charArray = hex.toCharArray();
        int length = charArray.length;
        int times = length / 2;
        for (int c1i = 0; c1i < times; c1i += 2) {
            int c2i = c1i + 1;
            char c1 = charArray[c1i];
            char c2 = charArray[c2i];
            int c3i = length - c1i - 2;
            int c4i = length - c1i - 1;
            charArray[c1i] = charArray[c3i];
            charArray[c2i] = charArray[c4i];
            charArray[c3i] = c1;
            charArray[c4i] = c2;
        }
        return new String(charArray);
    }

    /**
     * 拆分byte数组
     *
     * @param bytes 要拆分的数组
     * @param size  要按几个组成一份
     * @return byte[][]
     */
    private static List<byte[]> splitBytes(byte[] bytes, int size) {
        double splitLength = Double.parseDouble(size + "");
        int arrayLength = (int) Math.ceil(bytes.length / splitLength);

        List<byte[]> resultList = new ArrayList<>();
        int from, to;
        for (int i = 0; i < arrayLength; i++) {
            from = (int) (i * splitLength);
            to = (int) (from + splitLength);
            if (to > bytes.length)
                to = bytes.length;
            resultList.add(Arrays.copyOfRange(bytes, from, to));
        }
        return resultList;

    }
}
